import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import moment from 'moment'
import { Button, Space, message } from 'antd'
import { createExaminationApi } from '@/service/exam'
import type { ExaminationItem } from '@/service/type'
import type { paperlist, subjectslist, ClassType } from '@/services/type'
import styles from './PreView.module.scss'
interface Props {
  changeStep: (value: number, data?: any) => void // 切换步骤函数
  studentList: ClassType[] // 班级列表
  classifyList:subjectslist[] // 科目列表
  proctorList: paperlist[] // 监考人列表
}

interface SelectedPaper {
  _id: string
  name: string
  [key: string]: any
}

interface FormData {
  examName: string
  'range-time-picker': string[]
  subject: string
  class: string
  proctor: string
  selectedPaper?: SelectedPaper
}

const PreView: React.FC<Props> = ({ changeStep, studentList, classifyList, proctorList }) => {
  const [parseData, setParseData] = useState<FormData>()
  const navigate = useNavigate()
  useEffect(() => {
    const preViewData = localStorage.getItem('examFormData')
    console.log(studentList)
    if (preViewData) {
      setParseData(JSON.parse(preViewData))
    }
  }, [])

  const handleCreateExam = async () => {
    try {
      if (!parseData) return

      // 验证必填参数
      if (!parseData.examName || !parseData.subject || !parseData.selectedPaper?._id ||
        !parseData.class || !parseData.proctor || !parseData['range-time-picker']) {
        console.error('缺少必填参数')
        return
      }

      // 验证proctor是否为有效的ObjectId
      const isValidObjectId = (id: string) => /^[0-9a-fA-F]{24}$/.test(id);
      if (!parseData.proctor || !isValidObjectId(parseData.proctor)) {
        throw new Error('监考人ID格式无效，请返回上一步重新选择监考人');
      }

      // 准备API参数
      const apiParams = {
        name: parseData.examName.trim(),
        exam: parseData.selectedPaper?._id.trim() || '',
        class: parseData.class.trim(),
        subject: parseData.subject.trim(),
        startTime: moment(parseData['range-time-picker']?.[0]).valueOf(),
        endTime: moment(parseData['range-time-picker']?.[1]).valueOf(),
        proctor: parseData.proctor, // 移除trim()保持原始ObjectId
        settings: {
          allowLate: false,
          allowEarly: false,
          allowReview: true,
          allowDiscuss: false
        }
      }

      console.log('完整的请求参数包含subject:', apiParams.subject);

      console.log('完整的请求参数:', JSON.stringify(apiParams, null, 2))

      try {
        const response = await createExaminationApi(apiParams)
        if ( response.data.code !== 0 )
          {return console.log(response.data.msg)}
        console.log('考试创建成功', response.data)
        const resultData = {
          ...apiParams,
          id: response.data.data?.id
        }
        changeStep(1, resultData)
        localStorage.removeItem('examFormData')
        message.success('创建成功')
        navigate('/exam/record', { replace: true })
      } catch (error) {
        console.error('创建考试请求失败:', error)
      }
    } catch (error) {
      console.error('处理考试数据出错:', error)
    }
  }

  return (
    <div className={styles.preView}>
      <h1>配置信息</h1>
      <ul className={styles.configUl}>
        <li><p>考试名称：</p>{parseData?.examName}</li>
        <li><p>考试分类：</p>{classifyList![classifyList?.findIndex(Item => Item._id === parseData?.subject)]?.name}</li>
        <li><p>监考人员：</p>{proctorList![proctorList?.findIndex(Item => Item._id === parseData?.proctor)]?.username}</li>
        <li><p>班级：</p>{studentList![studentList?.findIndex(Item => Item._id === parseData?.class)]?.name}</li>
        <li className={styles.time}>
          考试时间：
          {parseData?.['range-time-picker'] && parseData['range-time-picker'].length === 2 ? (
            <div>
              <p>{moment(parseData['range-time-picker'][0]).format('YYYY-MM-DD HH:mm:ss')}</p>
              <p>{moment(parseData['range-time-picker'][1]).format('YYYY-MM-DD HH:mm:ss')}</p>
            </div>
          ) : '未设置'}
        </li>
      </ul>
      <Space>
        {/* 上一步按钮 */}
        <Button type="primary" onClick={() => changeStep(-1)}>上一步</Button>
        {/* 下一步按钮 */}
        <Button
          type="primary"
          onClick={handleCreateExam}
        >
          创建
        </Button>
      </Space>
    </div>
  )
}

export default PreView
